﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using LantinxShare.LBS.Location;
using LantixLBSServer.Web.DbAccess;
using LantinxShare.LBS;
using LantinxShare.Common;

namespace LantixLBSServer.Web
{
    public partial class AddressPage : System.Web.UI.Page
    {
        private string pathFile = "d:/loc.txt";
        private StringBuilder log = new StringBuilder();
        private bool SUCCESS = true;
        private void Write(String msg)
        {
            try
            {
                StreamWriter writer = new StreamWriter(pathFile, true);
                writer.WriteLine(msg);
                writer.Close();
            }
            catch
            {
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            log.Append("ddd");
            #region
            //UserManager manager = new UserManager();
            //manager.GetUsers();
            //var t = manager.GetUser("cx", "1");
            //RoleManager rolemanger = new RoleManager();
            //rolemanger.GetRoles();
            //MarkManager mark = new MarkManager();
            //mark.GetMarks();
            //LocationManager loc = new LocationManager();
            //loc.DeleteLocalById(1);
            #endregion
            this.Response.Clear();
            Process();
            Write(log.ToString());
            this.Response.End();
           
        }

        private void Process()
        {
            try
            {


                string option = this.Request.QueryString[GConstant.OP_OPTION];
                log.Append("option::" + option);
                string userId_str = this.Request.QueryString[GConstant.PM_User_Id];
                if (option != null)
                {
                    if (option == GConstant.OP_GET_LOCATION)
                    {
                        GetUserLocation(userId_str);
                    }
                    else if (option == GConstant.OP_SET_LOCATION)
                    {
                        SaveUserLocation(userId_str);
                    }
                    else if (option == GConstant.OP_GET_ROLE)
                    {
                        GetRoles();
                    }
                    else if (option == GConstant.OP_SET_ROLE)
                    {
                        SaveRole();
                    }
                    else if (option == GConstant.OP_EDIT_ROLE)
                    {
                        EditRole();
                    }
                    else if (option == GConstant.OP_DEL_ROLE)
                    {
                        RoleManager roleManager = new RoleManager();

                        roleManager.DeleteRole(new GRole()
                        {
                            RoleId = int.Parse(this.Request.Params["roleId"])
                        });
                    }
                    else if (option == GConstant.OP_SET_USER)
                    {
                        AddUser();
                    }
                    else if (option == GConstant.OP_EDIT_USER)
                    {
                        UpdateUser();
                    }
                    else if (option == GConstant.OP_DEL_USER)
                    {
                        UserManager manager = new UserManager();
                        manager.DeleteUserById(this.Request.Params["Id"]);
                    }
                    else if (option == GConstant.OP_GET_USER)
                    {
                        //只是测试了一下
                        //TaskManager taskManager = new TaskManager();
                        //taskManager.GetTaskByDate("20120527211700", "20120529211700");
                        GetUsers();
                    }
                    else if (option == GConstant.OP_GET_USER_PWD)
                    {
                        //只是测试了一下
                        String userName = this.Request.Params["name"];
                        String pwd = this.Request.Params["pwd"];
                        log.Append("userName" + userName);
                        //this.Response.Write(SUCCESS);
                         GetUser(userName, pwd);
                    }
                    else if (option == GConstant.OP_SET_MARK)
                    {
                        AddMark();
                    }
                    else if (option == GConstant.OP_GET_MARK)
                    {
                        GetMarks();
                    }
                    else if (option == GConstant.OP_DEL_MARK)
                    {
                        MarkManager manager = new MarkManager();
                        int id = int.Parse(this.Request.Params["id"]);
                        if (manager.DeleteMarkById(id))
                        {
                            this.Response.Write(SUCCESS);
                        }
                        else
                        {
                            this.Response.Write(!SUCCESS);
                        }
                    }
                    else if (option == GConstant.OP_GET_WORK_ITEM_TYPE)
                    {
                        WorkItemTypeManager workTypeManager = new WorkItemTypeManager();
                        List<GWorkItemType> list = workTypeManager.GetGWorkItemTypes();
                        if (list.Count > 0)
                        {
                            StringBuilder builder = new StringBuilder();
                            builder.Append(list[0]);
                            for (int i = 1; i < list.Count; i++)
                            {

                                builder.Append(G.P + list[i]);
                            }
                            this.Response.Write(builder.ToString());
                        }
                    }
                    else if (option == GConstant.OP_SET_WORK_ITEM_TYPE)
                    {
                        AddWorkItemType();
                    }
                    else if (option == GConstant.OP_SET_WORKITEM)
                    {
                        AddWorkItem();
                    }
                    else if (option == GConstant.OP_GET_LOCATION_DATE)
                    {
                        int id = int.Parse(this.Request.Params["userId"]);
                        DateTime date = DateTime.Parse(this.Request.Params["Date"]);
                        GetUserLocationDate(id, date);
                    }
                    else if (option == GConstant.OP_LOCATION_CLEAR)
                    {
                        this.Response.Write(SUCCESS);
                    }
                }
                else
                {
                    this.Response.Write(GetDefault());
                }
            }
            catch (Exception ex)
            {
                this.Response.Write(ex.ToString());
            }
        }

        private void AddWorkItemType()
        {
            WorkItemTypeManager workTypeManager = new WorkItemTypeManager();
            if (workTypeManager.InsertGWorkItemType(this.Request.Params["WorkItemName"], this.Request.Params["WorkType"], this.Request.Params["WorkLevel"]))
            {
                this.Response.Write(SUCCESS);
            }
            else
            {
                this.Response.Write(!SUCCESS);
            }
        }

        private void AddWorkItem()
        {
            TaskManager taskManager = new TaskManager();
            bool isSuccess = taskManager.InserTask(this.Request.Params["UserId"], this.Request.Params["MarkId"], this.Request.Params["StartDate"], this.Request.Params["EndDate"]);
            if (isSuccess)
            {
                int taskId = taskManager.GetTaskId(this.Request.Params["UserId"], this.Request.Params["MarkId"], this.Request.Params["StartDate"], this.Request.Params["EndDate"]);
                WorkItemManager workTypeManager = new WorkItemManager();
                string[] workTypeIds_str = this.Request.Params["WorkItems"].Split(',');
                foreach (var item in workTypeIds_str)
                {

                    workTypeManager.InsertWorkItem(taskId, new GWorkItem()
                    {
                        State = 0,
                        WorkItemType = new GWorkItemType() { Id = int.Parse(item) }

                    });
                }

                this.Response.Write(SUCCESS);
            }
            else
            {
                this.Response.Write(!SUCCESS);
            }
        }

        private void AddMark()
        {
            MarkManager manager = new MarkManager();
            GMark gmark = new GMark()
            {
                MarkName = this.Request.Params["markName"],
                Address = this.Request.Params["address"],
                Description = this.Request.Params["description"],

                Longitude = double.Parse(this.Request.Params["longitude"]),
                Latitude = double.Parse(this.Request.Params["latitude"]),
                Radius = double.Parse(this.Request.Params["radius"]),
                West = double.Parse(this.Request.Params["west"]),
                South = double.Parse(this.Request.Params["south"]),
                East = double.Parse(this.Request.Params["east"]),
                North = double.Parse(this.Request.Params["north"]),
                Altitude = double.Parse(this.Request.Params["altitude"])
            };

            manager.InsertMark(gmark);
            this.Response.Write(manager.GetMarkByMark(gmark).Id);
        }

        private void GetUsers()
        {
            UserManager manager = new UserManager();
            //int roleId = 0;
            //if (int.TryParse(this.Request.Params["RoleId"], out roleId))
            //{
            //    manager.InsertUser(this.Request.Params["UserName"], this.Request.Params["UserAlias"],
            //        this.Request.Params["Password"], this.Request.Params["Phone"], roleId);
            //}
            List<GUser> list = manager.GetUsers();
            if (list.Count > 0)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(list[0]);
                for (int i = 1; i < list.Count; i++)
                {

                    builder.Append(G.P + list[i]);
                }
                this.Response.Write(builder.ToString());
            }
        }
        private void GetUser(String alias, String pwd)
        {
            UserManager manager = new UserManager();
            GUser user = manager.GetUser(alias, pwd);
            if (user != null)
            {
                string u = user.ToString();
                this.Response.Write(u);
                log.Append("u::"+u);
                //this.Response.Write(SUCCESS);
            }
            else
            {
                log.Append("nou");
                this.Response.Write(string.Empty);
            }
        }

        private void UpdateUser()
        {
            UserManager manager = new UserManager();
            int userId = 0;
            if (int.TryParse(this.Request.Params["Id"], out userId))
            {

                GUser user = new GUser()
                {
                    Id = int.Parse(this.Request.Params["Id"]),
                    UserName = this.Request.Params["UserName"],
                    UserAlias = this.Request.Params["UserAlias"],
                    Password = this.Request.Params["Password"],
                    Phone = this.Request.Params["Phone"],
                    Role = new GRole() { RoleId = int.Parse(this.Request.Params["RoleId"]) }
                };
                manager.UpdateUser(user);
            }
        }

        private void AddUser()
        {
            UserManager manager = new UserManager();
            int roleId = 0;
            if (int.TryParse(this.Request.Params["RoleId"], out roleId))
            {
                manager.InsertUser(this.Request.Params["UserName"], this.Request.Params["UserAlias"],
                    this.Request.Params["Password"], this.Request.Params["Phone"], roleId);
            }
            this.Response.Write(manager.GetUser(this.Request.Params["UserAlias"], this.Request.Params["Password"]).ToString());
        }

        private void EditRole()
        {
            RoleManager roleManager = new RoleManager();

            roleManager.UpdateRole(new GRole()
            {
                RoleId = int.Parse(this.Request.Params["roleId"]),
                RoleName = this.Request.Params["roleName"]
            });
        }

        private void SaveRole()
        {
            RoleManager roleManager = new RoleManager();

            roleManager.InsertRole(this.Request.Params["roleName"]);
        }

        private void GetRoles()
        {
            RoleManager roleManager = new RoleManager();
            List<GRole> list = roleManager.GetRoles();
            if (list.Count > 0)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(list[0]);
                for (int i = 1; i < list.Count; i++)
                {

                    builder.Append(G.P + list[i]);
                }
                this.Response.Write(builder.ToString());
            }
        }

        private void GetMarks()
        {
            MarkManager roleManager = new MarkManager();
            List<GMark> list = roleManager.GetMarks();
            if (list.Count > 0)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(list[0]);
                for (int i = 1; i < list.Count; i++)
                {

                    builder.Append(G.P + list[i]);
                }
                this.Response.Write(builder.ToString());
            }
        }



        #region 保存位置
        private void SaveUserLocation(string userId_str)
        {
            string result = this.Request.Params[GConstant.PM_Params];
            if (result != null)
            {
                int userId = 0;
                if (int.TryParse(userId_str, out userId))
                {
                    List<GLocation> list = GLocation.GetGLocations(result);
                    List<GLocation> sourceList = GetSourceLocation(userId);
                    List<GLocation> newList = GLocation.CompareAdd(sourceList, list);

                    SaveGLocation(userId, newList);
                }

                this.Response.Write(SUCCESS);
            }
        }
        private void SaveGLocation(int userid, List<GLocation> sourceList)
        {
            LocationManager manager = new LocationManager();
            var user = new GUser() { Id = userid };

            foreach (var item in sourceList)
            {
                manager.InsertLocal(user, item);
            }

        }
        #endregion

        #region 得到位置
        private void GetUserLocationDate(int userId, DateTime date)
        {
            LocationManager manager = new LocationManager();
            List<GUserLocation> list = manager.GetLocationByUserIdDate(userId, date);
            //List<GLocation> addressList = new List<GLocation>();
            //foreach (var item in userLocationList)
            //{
            //    addressList.Add(item.Location);
            //}
            if (list.Count > 0)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(list[0]);
                for (int i = 1; i < list.Count; i++)
                {

                    builder.Append(G.P + list[i]);
                }
                this.Response.Write(builder.ToString());
            }
            //this.Response.Write( GLocation.GetGLocationString(addressList));
        }

        private void GetUserLocation(string userId_str)
        {
            int userId = 0;
            if (int.TryParse(userId_str, out userId))
            {
                this.Response.Write(GetUserLocation(userId));
            }
        }
        private String GetUserLocation(int userId)
        {
            LocationManager manager = new LocationManager();
            List<GUserLocation> userLocationList = manager.GetLocationByUserId(userId);
            List<GLocation> addressList = new List<GLocation>();
            foreach (var item in userLocationList)
            {
                addressList.Add(item.Location);
            }

            return GLocation.GetGLocationString(addressList);
        }
        private List<GLocation> GetSourceLocation(int userId)
        {
            LocationManager manager = new LocationManager();
            List<GLocation> list = new List<GLocation>();
            List<GUserLocation> userLocationList = manager.GetLocationByUserId(userId);
            foreach (var item in userLocationList)
            {
                list.Add(item.Location);
            }
            return list;
        }
        #endregion

        #region 设置默认值
        private String GetDefault()
        {
            return @"a,121.478759938092,31.2039347917019,201205231317,5.0,31.05|
                                  b,121.479759938092,31.2079347917019,201205231317,5.0,0|
                                  c,121.479739938092,31.2179347917019,201205231317,5.0,31.05|
                                  d,121.479759938092,31.2089348917019,201205231317,5.0,0|
                                  e,121.479759938092,31.2099347917019,201205231317,5.0,31.05";
        }
        #endregion
    }// end for class
}// end for namespace